class Annoration < ActiveRecord::Base

    belongs_to :user
    belongs_to :page

    ###############################################
    # virtual attribute for the uri
    def uri
      page.uri
    end
    
    def uri=(new_uri)
        @uri_errors = Array.new
        @uri_value = format_uri(@uri_errors, new_uri, 'source')
        web_page = Page.find_or_create_by_uri(@uri_value)
        if !process_errors(web_page, @uri_errors)
            self.page = web_page 
        end
    end
    
    protected
    
    ###############################################
    # formats and validates a uri
    def format_uri(error_array, new_uri, type)
        begin
            if new_uri.nil? || new_uri.length <= 0
                error_array.push('Please enter a value for the ' + type + ' url.')
            else
                uri = URI.parse(new_uri)
                if uri.scheme.nil?
                    new_uri = "http://" + new_uri
                    uri = URI.parse(new_uri)
                end                
                
                if uri.class != URI::HTTP && uri.class != URI::HTTPS && uri.class != URI::FTP
                    error_array.push('Please use an valid url for the ' + type + ' url.  i.e. http://www.example.com.  Also, Please be sure to include the "http".')
                end
            end
        rescue URI::InvalidURIError
            error_array.push('The format of the ' + type + ' url is not valid.')
        end
        uri.to_s     
    end
    
    ###############################################
    # Adds errors from the model into the current
    # objects errors.  Returns false if no errors were
    # found.  True if errors were found.
    def process_errors(record, error_array)
        if record.errors.length > 0
            record.errors.each do |error|
                @from_uri_errors.push(error[1])
            end
            return true
        else
            return false
        end
    end
    
end
